package wens.pig.dhm.formplugin.patrolscheme;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.events.PackageDataEvent;
import kd.bos.entity.report.CellStyle;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.BeforeCreateListColumnsArgs;
import kd.bos.form.events.FilterColumnSetFilterEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.list.BillList;
import kd.bos.list.IListColumn;
import kd.bos.list.ListShowParameter;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.mvc.list.ListView;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.lang3.StringUtils;
import wens.pig.base.common.consts.SysConst;
import wens.pig.base.common.consts.dhm.PatrolPlanConstant;
import wens.pig.base.common.enums.EnvPlanExeStatusEnum;
import wens.pig.base.utils.PigGeryUtil;
import wens.pig.base.utils.ToolUtils;

import java.util.*;

import static wens.pig.base.common.consts.BaseDataConst.F_ID;
import static wens.pig.base.common.consts.BaseDataConst.F_NAME;
import static wens.pig.base.common.consts.OperationConst.REFRESH;

/**
 * 巡查计划列表页面插件
 * coyle
 */
public class PatrolPlanListPlugin extends AbstractListPlugin {
    private static final String ORG_FIELD = "wens_org";
    private static final String WENROLE = "wens_role";
    private static final ThreadLocal<List<DynamicObject>> LIST_DATA = new ThreadLocal<>();
    private static final ThreadLocal<List<IListColumn>> LIST_FIELDS = new ThreadLocal<>();
    private static final Map<String, String> ENTRY_STATUS_MAP = new HashMap<>();
    private static final String F_SEQ = "fseq";
    private static final String EXESTATE = "wens_exestate_head";
    private static final String BILLCANCEL = "wens_cancelplanbut";
    private static final List<String> EXESTATEVAL = Arrays.asList(
            EnvPlanExeStatusEnum.EXEING.getValue(),
            EnvPlanExeStatusEnum.NOSTART.getValue()
    );
    private static final String TBLSHOWBILL = "wens_tblshowbill";// 显示整单
    private static final String TBLSHOWONE = "wens_tblshowone";// 显示一行
    String[]  showParam = {"wens_productline.name",
            "wens_two.name","wens_pigsty.name","wens_site.name",
            "wens_sampdate","wens_sampuser.name","wens_sambillno",
            "wens_result", "wens_place","wens_three.name","wens_sitedetails"};
//    String[]  showCol = {"wens_productline_name",
//            "wens_two_name","wens_pigsty_name","wens_site_name",
//            "wens_sampdate","wens_sampuser_name","wens_sambillno",
//            "wens_result", "wens_place","wens_three_name","wens_sitedetails"};
    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        if(StringUtils.equals( itemKey ,BILLCANCEL)) {
            DynamicObjectCollection dynamicObjects = new DynamicObjectCollection();
            HashSet<String> noPassNumList = new HashSet<>();
            HashSet<String> billNumList = new HashSet<>();
            ListSelectedRowCollection collection = getSelectedRows();
            for(ListSelectedRow objRow: collection){
                DynamicObject planObj = BusinessDataServiceHelper.loadSingle(objRow.getPrimaryKeyValue(), PatrolPlanConstant.FORMBILLID);
                String exeStatus = planObj.getString(PatrolPlanConstant.WENS_EXESTATE_HEAD);
                if(!EXESTATEVAL.contains(exeStatus)){
                    noPassNumList.add(planObj.getString("billno"));
                }
                int sampledqty = planObj.getInt("wens_sampledqty");
                if(sampledqty > 0 ){
                    billNumList.add(planObj.getString("billno"));
                }
                dynamicObjects.add(planObj);
            }

            if(noPassNumList.size() > 0 ){
                this.getView().showErrorNotification("编码为:"+ ToolUtils.aryToStr(noPassNumList,true)+"的计划不能作废(只能作废计划状态为<未开始>与<执行中>的数据);");
                return;
            }
            if(billNumList.size() > 0 ){
                this.getView().showTipNotification("编码为:"+ToolUtils.aryToStr(billNumList,true)+"的计划,已生成<巡查记录>,请先删除对应单据,再执行作废!",5000);
               /* ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener(BILLCANCEL, this);
                this.getView().showConfirm("编码为:"+ToolUtils.aryToStr(billNumList,true)+"的计划,已完成部分采样，是否仍需作废?", MessageBoxOptions.YesNo,
                        ConfirmTypes.Default, confirmCallBacks);*/
            }else{
                ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener(BILLCANCEL, this);
                this.getView().showConfirm("是否确认作废此数据?", MessageBoxOptions.YesNo,
                        ConfirmTypes.Default, confirmCallBacks);
            }
        }
    }


    @Override
    public void afterCreateNewData(EventObject e) {
        ListView listView = (ListView) this.getView();
        MainEntityType dataType = EntityMetadataCache.getDataEntityType(listView.getBillFormId());
        this.getPageCache().put(ORG_FIELD, dataType.getMainOrg());
        this.getView().setVisible(true,TBLSHOWONE);
        this.getView().setVisible(false,TBLSHOWBILL);
    }

    @Override
    public void filterColumnSetFilter(SetFilterEvent args) {
        ListShowParameter parameter = (ListShowParameter) this.getView().getFormShowParameter();
        if (parameter.isLookUp()) {
            return;
        }
        // 猪场字段
        String pigGeryFieldName = this.getPageCache().get(ORG_FIELD);
        // 猪场过滤
        if (args.getFieldName().startsWith(pigGeryFieldName)) {
            args.addCustomQFilter(new QFilter(F_ID, QCP.in, PigGeryUtil.getPermPigGeryOrgList()));
        }
        //过滤采样组
        if (args.getFieldName().startsWith(WENROLE)) {
            ArrayList<String> pigGeryIds = this.getOrgId((FilterColumnSetFilterEvent) args, pigGeryFieldName);
            if(pigGeryIds.size()>0){
                String orgVal = pigGeryIds.get(0);
                if(!StringUtils.isBlank(orgVal)){ //如果为空,是"不限",那么不用过滤
                    args.addCustomQFilter(new QFilter(ORG_FIELD, QCP.in, pigGeryIds));
                }
            }
        }
    }

    /**
     *获取组织;
     */
    private ArrayList<String> getOrgId(FilterColumnSetFilterEvent args, String pigGeryFieldName) {
        String fieldName = pigGeryFieldName + SysConst.SPOT + F_NAME;
        ArrayList<String> pigGeryIds = args.getCommonFilterValue(fieldName) == null? new ArrayList(): (ArrayList)args.getCommonFilterValue(fieldName) ;
        return pigGeryIds;
    }

    @Override
    public void beforeCreateListColumns(BeforeCreateListColumnsArgs args) {
        LIST_FIELDS.set(args.getListColumns());
        //删除分录
        removeColumns(args);
    }

    @Override
    public void packageData(PackageDataEvent e) {
        List<DynamicObject> listData = LIST_DATA.get();
        if (listData == null) {
            listData = new ArrayList<>();
            LIST_DATA.set(listData);
        }
        if (e.getRowData().getInt(F_SEQ) > listData.size()) {
            listData.add(e.getRowData());
        }
    }


    @Override
    public void afterBindData(EventObject e) {
        BillList billList = this.getControl(AbstractListPlugin.BILLLISTID);
        List<DynamicObject> listData = LIST_DATA.get();
        List<IListColumn> fields = LIST_FIELDS.get();
        LIST_DATA.remove();
        LIST_FIELDS.remove();
        if (listData == null || fields == null) {
            return;
        }
        //获得列表所有的字段
        ListView view = (ListView) this.getView();
        List<CellStyle> csList = new ArrayList<>();
        int pageRow = billList.getPageRow();
        Integer currentPageIndex = billList.getEntryState().getCurrentPageIndex();
        pageRow = (currentPageIndex - 1) * pageRow;
        for (int i=0; i<listData.size(); i++) {
            String exeStatus = listData.get(i).getString(EXESTATE);
            int b = 0;
            if(EnvPlanExeStatusEnum.EXEING.getValue().equals(exeStatus) ){
                b = 1 ;
            }
            for (IListColumn field : fields) {
                CellStyle cs = new CellStyle();
                cs.setFieldKey(field.getListFieldKey().replace(".", "_"));
                if(b==1){
                    cs.setBackColor("#00FF00");
                }
                cs.setRow(pageRow+i);
                csList.add(cs);
            }
        }
        billList.setCellStyle(csList);
    }



    /**
     * 作废
     * @param dynamicObjects
     * coyle
     * 202312
     */
    private  void  setCancelBill(DynamicObjectCollection dynamicObjects){
        this.getView().invokeOperation("cancelplan");
        this.getView().invokeOperation(REFRESH);
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent evt) {
        super.confirmCallBack(evt);
        if (StringUtils.equals(BILLCANCEL, evt.getCallBackId())
                && evt.getResult() == MessageBoxResult.Yes){
            DynamicObjectCollection dynamicObjects = new DynamicObjectCollection();
            ListSelectedRowCollection collection = getSelectedRows();
            for(ListSelectedRow objRow: collection){
                DynamicObject planObj = BusinessDataServiceHelper.loadSingle(objRow.getPrimaryKeyValue(), PatrolPlanConstant.FORMBILLID);
                dynamicObjects.add(planObj);
            }
            setCancelBill(dynamicObjects);
        }
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        String itemKey = evt.getItemKey();
        switch (itemKey) {
            case TBLSHOWBILL:
                this.getPageCache().put("itemKey",TBLSHOWBILL);
                this.getView().setVisible(true,TBLSHOWONE);
                this.getView().setVisible(false,TBLSHOWBILL);
                break;
            case TBLSHOWONE:
                this.getPageCache().put("itemKey",TBLSHOWONE);
                this.getView().setVisible(false,TBLSHOWONE);
                this.getView().setVisible(true,TBLSHOWBILL);
                break;
            default:
                break;
        }
    }


    /**
     * 删除分录列
     * @param args
     */
    private void removeColumns(BeforeCreateListColumnsArgs args) {
        List<IListColumn> columns = args.getListColumns();
        if(StringUtils.equals(this.getPageCache().get("itemKey"),TBLSHOWONE)){
            for(String param:showParam){
                columns.remove(args.getListColumn(param));
            }
        }
        super.beforeCreateListColumns(args);

    }

}
